package fu.k4c.vTeam.ViewDetails;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Main.BaseActivity;
import fu.k4c.vTeam.Main.ViewEventActivity;
import fu.k4c.vTeam.Manage.CreateEventActivity;
import fu.k4c.vTeam.Object.Account;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

public class ImagePagerActivity extends BaseActivity {

	private ViewPager pager;
	String[] idImageUrls;
	String email;
	String createBy;
	Button btn_delete;
	private int currentPage;

	private DisplayImageOptions options;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_image_pager);

		Bundle bundle = getIntent().getExtras();
		String[] imageUrls = bundle.getStringArray("imageURL");
		idImageUrls = bundle.getStringArray("id");
		int pagerPosition = bundle.getInt("position", 0);
		email = bundle.getString("email");
		createBy = bundle.getString("createBy");
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheOnDisc().imageScaleType(ImageScaleType.IN_SAMPLE_INT)
				.build();
		currentPage = pagerPosition;
		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(new ImagePagerAdapter(imageUrls));
		pager.setCurrentItem(pagerPosition);
		pager.setOnPageChangeListener(new DetailOnPageChangeListener());

	}

	private class ImagePagerAdapter extends PagerAdapter {

		private String[] images;
		private LayoutInflater inflater;

		ImagePagerAdapter(String[] images) {
			this.images = images;
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object instantiateItem(final View view, final int position) {
			final View imageLayout = inflater.inflate(
					R.layout.item_pager_image, null);
			final ImageView imageView = (ImageView) imageLayout
					.findViewById(R.id.image);
			final ProgressBar spinner = (ProgressBar) imageLayout
					.findViewById(R.id.loading);
			btn_delete = (Button) imageLayout
					.findViewById(R.id.btn_item_pager_delete);
			btn_delete.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (email.equals(createBy)) {

						new AlertDialog.Builder(ImagePagerActivity.this)
								.setMessage("Bạn muốn xóa ảnh này không?")
								.setPositiveButton("Có",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												try {
													SchemeRegistry registry = new SchemeRegistry();
													registry.register(new Scheme(
															"http",
															PlainSocketFactory
																	.getSocketFactory(),
															80));
													HttpParams httpParams = new BasicHttpParams();
													ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
															httpParams,
															registry);
													HttpClient client = new DefaultHttpClient(
															connMgr, httpParams);
													HttpPost post = new HttpPost(
															getString(R.string.connectionString)
																	+ "vLocationService/DeleteImage");
													post.setHeader("Accept",
															"application/json");
													post.setHeader(
															"Content-type",
															"application/json");
													HashMap<String, Object> postParameters = new HashMap<String, Object>();
													postParameters
															.put("imageID",
																	idImageUrls[currentPage]);
													postParameters.put(
															"userEmail", email);
													Gson gson = new Gson();
													String jsonParameters = gson
															.toJson(postParameters);
													post.setEntity(new StringEntity(
															jsonParameters));
													HttpResponse response = client
															.execute(post);
													HttpEntity entity = response
															.getEntity();
													String jsonresult = EntityUtils
															.toString(entity);
													Account status = gson
															.fromJson(
																	jsonresult,
																	Account.class);
													if (status.getStatus()
															.equals("True")) {
														// destroyItem(view,
														// position,
														// imageLayout);
														Toast.makeText(
																getApplicationContext(),
																"Xóa ảnh thành công",
																Toast.LENGTH_LONG)
																.show();
														Intent i = new Intent(
																ImagePagerActivity.this,
																ImageActivity.class);
														setResult(RESULT_OK, i);
														finish();
													} else {
														Toast.makeText(
																getApplicationContext(),
																"Xóa ảnh lỗi",
																Toast.LENGTH_LONG)
																.show();
													}
												} catch (Exception e) {
													// TODO: handle exception
													Toast.makeText(
															getApplicationContext(),
															"Xóa ảnh lỗi",
															Toast.LENGTH_LONG)
															.show();
												}

											}
										})
								.setNegativeButton("Không",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
											}
										}).create().show();
					} else
						Toast.makeText(getApplicationContext(),
								"Bạn không có quyền xóa ảnh này!",
								Toast.LENGTH_LONG).show();
				}
			});
			// Toast.makeText(ImagePagerActivity.this, "" + position,
			// Toast.LENGTH_SHORT).show();
			imageLoader.displayImage(images[position], imageView, options,
					new ImageLoadingListener() {
						public void onLoadingStarted() {
							spinner.setVisibility(View.VISIBLE);

						}

						public void onLoadingFailed(FailReason failReason) {
							String message = null;
							switch (failReason) {
							case IO_ERROR:
								message = "Input/Output error";
								break;
							case OUT_OF_MEMORY:
								message = "Out Of Memory error";
								break;
							case UNKNOWN:
								message = "Unknown error";
								break;
							}
							Toast.makeText(ImagePagerActivity.this, message,
									Toast.LENGTH_SHORT).show();

							spinner.setVisibility(View.GONE);
							imageView
									.setImageResource(android.R.drawable.ic_delete);
						}

						public void onLoadingComplete(Bitmap loadedImage) {
							spinner.setVisibility(View.GONE);
							Animation anim = AnimationUtils.loadAnimation(
									ImagePagerActivity.this, R.anim.fade_in);
							imageView.setAnimation(anim);
							anim.start();
						}

						public void onLoadingCancelled() {
							// Do nothing
						}
					});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent i = new Intent(ImagePagerActivity.this, ImageActivity.class);
			setResult(RESULT_CANCELED, i);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public class DetailOnPageChangeListener extends
			ViewPager.SimpleOnPageChangeListener {

		@Override
		public void onPageSelected(int position) {
			currentPage = position;
			// Toast.makeText(getApplicationContext(),
			// ""+idImageUrls[currentPage], Toast.LENGTH_LONG).show();
		}

		public int getCurrentPage() {

			return currentPage;
		}
	}

}